package com.example.demo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Classname MySecurityConfig
 * @Description TODO
 * @Date 2020/8/1 10:39
 * @Created by pc
 */
@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        http.httpBasic()
                .and()
                .authorizeRequests()
                // 放行登录页
                .antMatchers("/login")
                .permitAll()
                // 其他路径访问都要经过授权
                .anyRequest()
                .authenticated()
                .and()
                // 表单登录
                .formLogin()
                .loginPage("/login")
                // 登陆成功处理器
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter writer = response.getWriter();
                        ObjectMapper om = new ObjectMapper();
//                        String successMsg = om.writeValueAsString(om.writeValueAsString(authentication));
//                        writer.write(successMsg);
//                        writer.flush();
//                        writer.close();
                        String requestURI = request.getRequestURI();
                        response.sendRedirect("/");
                    }
                })
                // 登陆失败处理器
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter writer = resp.getWriter();
//                        writer.write(new ObjectMapper().writeValueAsString(e));
                        writer.write("登录失败!!!");
                        writer.flush();
                        writer.close();
                    }
                })
                .loginProcessingUrl("/show")
                .and()
                .csrf().disable();

    }

    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
